package com.gr.catanddog_common.exception;


import com.gr.catanddog_common.utils.Response;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.naming.Binding;
import java.util.Optional;

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler({Exception.class})
    @ResponseBody
    public Response<Object> handleBisException(HttpServletRequest request, Exception e){
        log.warn("{} request fail,errorMessage: {}",request.getRequestURL(),e.getMessage());
        return  Response.fail(new BisException().getMessage());
    }

    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseBody
    public Response<Object> handleMethodArgumentNotValidException(HttpServletRequest request,MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        StringBuilder sb = new StringBuilder();
        Optional.ofNullable(bindingResult.getFieldErrors()).ifPresent(errors->{
            errors.forEach(error ->
                    sb.append(error.getField())
                            .append(" ")
                            .append(error.getDefaultMessage())
                            .append(", 当前值：’")
                            .append(error.getRejectedValue())
                            .append("’；")
                    );
        });
        String errorMsg = sb.toString();
        log.warn("{} request error,  errorMessage: {}", request.getRequestURI(), errorMsg);

        return Response.fail(errorMsg);
    }

}
